#coding:utf-8
'''
* coder  : Dzlua
* email  : 505544956@qq.com
* module : api-frame
* path   : app/models
* file   : user.py
* time   : 2017/10/21
'''
#--------------------#
from app import mgr
#--------------------#

#--------------------#
class User(mgr.db.Model):
    __tablename__ = 'users'
    #----------#
    id = mgr.db.Column(mgr.db.Integer, primary_key = True)
    name = mgr.db.Column(mgr.db.String(32), unique=True, nullable=False, index=True)
    pwd = mgr.db.Column(mgr.db.String(128), nullable=False)
    #----------#
    def hash_password(self, password):
        self.pwd = mgr.hash(password)
    def verify_password(self, password):
        return mgr.verify(password, self.pwd)
    #----------#
    def auth_token(self, expiration=600):
        s = mgr.Serializer(mgr.app.config['SECRET_KEY'], expires_in=expiration)
        return s.dumps({'id': self.id})
    @staticmethod
    def verify_auth_token(token):
        s = mgr.Serializer(mgr.app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except mgr.SignatureExpired:
            return None    # valid token, but expired
        except mgr.BadSignature:
            return None    # invalid token
        user = User.query.get(data['id'])
        return user
#--------------------#

#--------------------#
@mgr.auth.verify_password
def verify_password(username_or_token, password):
    user = User.verify_auth_token(username_or_token)
    if not user:
        user = User.query.filter_by(name=username_or_token).first()
        if not user or not user.verify_password(password):
            return False
    mgr.g.user = user
    return True
#----------#
@mgr.auth.error_handler
def unauthorized():
    return mgr.make_response(mgr.jsonify({'error': 'Unauthorized access'}), 401)
#--------------------#
    